﻿using CGT.GOP.App_Start;
using CGT.GOP.Common;
using CGT.GOP.Models;
using CGT.Infrastructure.Dto;
using CGT.Infrastructure.Entity;
using CGT.Infrastructure.Model;
using CGT.Infrastructure.Service;
using Dapper.Extensions;
using OF.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CGT.GOP.Controllers
{
    public class AuthorityController : BaseController
    {
        GovMenuService menuService = new GovMenuService();
        GovRoleTypeService roleTypeService = new GovRoleTypeService();
        GovRoleService roleService = new GovRoleService();
        GovRoleMenuRelaService relaService = new GovRoleMenuRelaService();
        GovLogOperateService loService = new GovLogOperateService();
        GovLogSafeService lsService = new GovLogSafeService();
        private int Mcode = 10102;//菜单管理编码
        private int Rcode = 10103;//角色管理编码

        #region 菜单
        [Authentication(MenuCode = 10102)]
        public ActionResult MenuList()
        {
            loService.Info(CurrentUser.UserId, "访问页面", 4, "", "访问菜单列表页面", Mcode);
            lsService.Info(CurrentUser.UserId, "访问页面", 4, "", "访问菜单列表页面", Mcode);
            return View();
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetMenuList()
        {
            ResultData<List<MenuInfo>> rData = new ResultData<List<MenuInfo>>();
            List<MenuInfo> mlist = new List<MenuInfo>();
            MenuInfo menuObj = null;
            IList<GovMenu> list = menuService.GetValidList();
            //父级菜单
            var ParentList = from AuthorityMenu in list
                             where AuthorityMenu.ParentID == 0
                             select new { MenuName = AuthorityMenu.MenuName, MenuID = AuthorityMenu.MenuID, MenuUrl = AuthorityMenu.MenuUrl };
            foreach (var pv in ParentList)
            {
                List<ChildMenu> clist = new List<ChildMenu>();
                menuObj = new MenuInfo
                {
                    MenuName = pv.MenuName,
                    MenuID = pv.MenuID,
                    MenuUrl = pv.MenuUrl
                };
                //子级菜单
                var ChildList = from AuthorityMenu in list
                                where AuthorityMenu.ParentID == pv.MenuID
                                select new { MenuName = AuthorityMenu.MenuName, MenuID = AuthorityMenu.MenuID, MenuUrl = AuthorityMenu.MenuUrl, MenuCode = AuthorityMenu.MenuCode };
                foreach (var item in ChildList)
                {
                    ChildMenu obj = new ChildMenu
                    {
                        MenuName = item.MenuName,
                        MenuID = item.MenuID,
                        MenuUrl = item.MenuUrl
                    };
                    clist.Add(obj);
                }
                menuObj.ChildMenu = clist;
                mlist.Add(menuObj);
            }
            rData.data = mlist;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 获取父级菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetParentMenuList()
        {
            ResultData<IList<GovMenu>> rData = new ResultData<IList<GovMenu>>();
            IList<GovMenu> list = menuService.GetParentList();
            rData.data = list;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 根据父级ID获取菜单
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetMenuListByParentId(int parentId)
        {
            ResultData<IList<GovMenu>> rData = new ResultData<IList<GovMenu>>();
            IList<GovMenu> list = menuService.QueryAll();
            rData.data = list.Where(a => a.ParentID == parentId && a.IsActive == 1).ToList();
            return ReturnResult(rData);
        }

        /// <summary>
        /// 获取所属类别
        /// </summary>
        /// <returns></returns>
        public ContentResult GetRoleTypeList()
        {
            ResultData<IList<GovRoleType>> rData = new ResultData<IList<GovRoleType>>();
            IList<GovRoleType> list = roleTypeService.QueryAll();
            rData.data = list;
            return ReturnResult(rData);
        }

        public ActionResult MenuEdit()
        {
            int id = EConvert.ToInt(GetParam("id"));
            int pId = EConvert.ToInt(GetParam("pid"));
            GovMenu menuObj = null;
            if (id > 0)
            {
                menuObj = menuService.Single(id);
                loService.Info(CurrentUser.UserId, "访问修改菜单页面", 4, "", string.Format("菜单页面:{0}", menuObj.MenuName), Mcode);
            }
            if (menuObj == null)
            {
                menuObj = new GovMenu();
                loService.Info(CurrentUser.UserId, "访问添加菜单页面", 4, "", string.Format("访问菜单ID:{0},添加子菜单页面", pId), Mcode);
            }
            ViewBag.Pid = pId;
            return View(menuObj);
        }

        /// <summary>
        /// 保存菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ContentResult SaveMenu(MenuModel model)
        {
            ResultData<int> rData = new ResultData<int>();
            GovMenu info = menuService.Single(model.MenuID);
            try
            {
                if (info == null)
                {
                    info = new GovMenu();
                    info.MenuName = model.txtName;
                    info.IsActive = 1;
                    info.CreateDateTime = DateTime.Now;
                    info.IsConventional = model.drpIsConventional;
                    info.IsCoreFunction = model.drpIsCoreFunction;
                    info.MenuType = 2;
                    info.MenuUrl = model.txtURL;
                    info.UpdateTime = DateTimeHelper.MinDateTime();
                    info.RoleTypeID = model.drpCategory;
                    info.OnlyForPolice = model.drpOnlyPolice;
                    info.OrderNum = model.txtOrderNum;
                    info.ParentID = model.selParentId;
                    info.MenuCode = model.txtMenuCode;
                    object id = menuService.Insert(info);
                    loService.Info(CurrentUser.UserId, "添加菜单", 1, string.Format("添加成功,返回ID:{0}", id), string.Format("{0}添加菜单{1},id:{2}", CurrentUser.UserName, info.MenuName, id), Mcode);
                    lsService.Info(CurrentUser.UserId, "添加菜单", 1, string.Format("添加成功,返回ID:{0}", id), string.Format("{0}添加菜单{1},id:{2}", CurrentUser.UserName, info.MenuName, id), Mcode);

                }
                else
                {
                    var oldinfo = ObjectCopy<GovMenu>.DeepCopy(info);
                    info.MenuName = model.txtName;
                    info.IsConventional = model.drpIsConventional;
                    info.IsCoreFunction = model.drpIsCoreFunction;
                    info.MenuUrl = model.txtURL;
                    info.UpdateTime = DateTime.Now;
                    info.RoleTypeID = model.drpCategory;
                    info.OnlyForPolice = model.drpOnlyPolice;
                    info.OrderNum = model.txtOrderNum;
                    info.ParentID = model.selParentId;
                    info.MenuCode = model.txtMenuCode;
                    menuService.Update(info);

                    loService.Info(CurrentUser.UserId, "修改菜单", 3, "成功", oldinfo, info, Mcode);
                    lsService.Info(CurrentUser.UserId, "修改菜单", 3, "操作成功", string.Format("{0}修改菜单{1}成功", CurrentUser.UserName, info.MenuName), Mcode);

                }
            }
            catch (Exception ex)
            {
                rData.status = -1;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 验证编码是否重复
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult IsExistCode(int mid,int code)
        {
            ResultData<string> rData = new ResultData<string>();
            if (mid > 0)
            {
                //修改时先验证是否跟当前代码相同，如果不同则验证是否重复
                GovMenu menuObj = menuService.Single(mid);
                if (menuObj != null)
                {
                    if (menuObj.MenuCode != code)
                    {
                        bool isExist = menuService.CheckMenuCode(code);
                        if (!isExist)
                        {
                            rData.status = -1;
                            rData.message = "编码不存在";
                        }
                    }
                    else
                    {
                        rData.status = -1;
                        rData.message = "修改时编码没变化";
                    }
                }
            }
            else
            {
                bool isExist = menuService.CheckMenuCode(code);
                if (!isExist)
                {
                    rData.status = -1;
                    rData.message = "编码不存在";
                }
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelMenu(int mid)
        {
            ResultData<string> rData = new ResultData<string>();
            if (mid < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
            }
            else
            {
                GovMenu menuObj = menuService.Single(mid);
                if (menuObj != null)
                {
                    menuObj.IsActive = 0;
                    menuObj.UpdateTime = DateTime.Now;
                    menuService.Update(menuObj);
                    //删除子菜单
                    if (menuObj.ParentID==0)
                    {
                        menuService.DelGovMenuByParentId(mid);
                    }
                  
                    loService.Info(CurrentUser.UserId, "删除菜单", 2, "删除成功", string.Format("{0}删除菜单({1}),数据ID:{2}", CurrentUser.UserName, menuObj.MenuName, menuObj.MenuID), Mcode);
                    lsService.Info(CurrentUser.UserId, "删除菜单", 2, "删除成功", string.Format("{0}删除菜单({1}),数据ID:{2}", CurrentUser.UserName, menuObj.MenuName, menuObj.MenuID), Mcode);

                }
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetRoleMenuRelaList(int roleId)
        {
            ResultData<List<RoleMenuRelaInfo>> rData = new ResultData<List<RoleMenuRelaInfo>>();
            List<RoleMenuRelaInfo> mlist = new List<RoleMenuRelaInfo>();
            RoleMenuRelaInfo menuObj = null;
            IList<GovRoleMenuRelaDto> list = menuService.GetRoleMenuRelaList(roleId);
            //父级菜单
            var ParentList = from AuthorityMenu in list
                             where AuthorityMenu.ParentID == 0
                             select new { MenuName = AuthorityMenu.MenuName, MenuID = AuthorityMenu.MenuID, MenuUrl = AuthorityMenu.MenuUrl,RelaId= AuthorityMenu.RelaID };
            foreach (var pv in ParentList)
            {
                List<RoleChildMenu> clist = new List<RoleChildMenu>();
                menuObj = new RoleMenuRelaInfo
                {
                    MenuName = pv.MenuName,
                    MenuID = pv.MenuID,
                    MenuUrl = pv.MenuUrl,
                    RelaId = pv.RelaId
                };
                //子级菜单
                var ChildList = from AuthorityMenu in list
                                where AuthorityMenu.ParentID == pv.MenuID
                                select new { MenuName = AuthorityMenu.MenuName, MenuID = AuthorityMenu.MenuID, MenuUrl = AuthorityMenu.MenuUrl, MenuCode = AuthorityMenu.MenuCode, RelaId = AuthorityMenu.RelaID };
                foreach (var item in ChildList)
                {
                    RoleChildMenu obj = new RoleChildMenu
                    {
                        MenuName = item.MenuName,
                        MenuID = item.MenuID,
                        MenuUrl = item.MenuUrl,
                        RelaId = item.RelaId
                    };
                    clist.Add(obj);
                }
                menuObj.ChildMenu = clist;
                mlist.Add(menuObj);
            }
            rData.data = mlist;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 根据角色ID获取菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetUserMenuList()
        {
            ResultData<List<MenuInfo>> rData = new ResultData<List<MenuInfo>>();
            List<MenuInfo> mlist = new List<MenuInfo>();
            MenuInfo menuObj = null;
            IList<GovMenu> list = menuService.GetUserMenuList(CurrentUser.RoleID);
            //父级菜单
            var ParentList = from AuthorityMenu in list
                             where AuthorityMenu.ParentID == 0
                             select new { MenuName = AuthorityMenu.MenuName, MenuID = AuthorityMenu.MenuID, MenuUrl = AuthorityMenu.MenuUrl };
            foreach (var pv in ParentList)
            {
                List<ChildMenu> clist = new List<ChildMenu>();
                menuObj = new MenuInfo
                {
                    MenuName = pv.MenuName,
                    MenuID = pv.MenuID,
                    MenuUrl = pv.MenuUrl,
                };
                //子级菜单
                var ChildList = from AuthorityMenu in list
                                where AuthorityMenu.ParentID == pv.MenuID
                                select new { MenuName = AuthorityMenu.MenuName, MenuID = AuthorityMenu.MenuID, MenuUrl = AuthorityMenu.MenuUrl, MenuCode = AuthorityMenu.MenuCode };
                foreach (var item in ChildList)
                {
                    ChildMenu obj = new ChildMenu
                    {
                        MenuName = item.MenuName,
                        MenuID = item.MenuID,
                        MenuUrl = item.MenuUrl,
                    };
                    clist.Add(obj);
                }
                menuObj.ChildMenu = clist;
                mlist.Add(menuObj);
            }
            rData.data = mlist;
            return ReturnResult(rData);
        }
        #endregion

        #region 角色
        [Authentication(MenuCode = 10103)]
        public ActionResult RoleList()
        {
            loService.Info(CurrentUser.UserId, "访问页面", 4, "", "访问角色列表页面", Rcode);
            lsService.Info(CurrentUser.UserId, "访问页面", 4, "", "访问角色列表页面", Rcode);
            return View();
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        public ContentResult GetRoleList()
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<GovRoleModel> page = roleService.GetPages(pageIndex, pageSize);
            return ReturnResult(new ResultPageData<List<GovRoleModel>>
            {
                data = page.rows,
                total = page.total
            });
        }

        /// <summary>
        /// 角色编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult RoleEdit()
        {
            int id = EConvert.ToInt(GetParam("id"));
            string des = string.Format("{0}添加角色", CurrentUser.UserName);
            GovRole roleObj = null;
            if (id > 0)
            {
                roleObj = roleService.Single(id);
                des = string.Format("{0}修改角色{1}", CurrentUser.UserName, roleObj.RoleName);
            }
            if (roleObj == null)
            {
                roleObj = new GovRole();
            }
            loService.Info(CurrentUser.UserId, "访问页面", 4, "", des, Rcode);
            lsService.Info(CurrentUser.UserId, "访问页面", 4, "", des, Rcode);
            return View(roleObj);
        }

        /// <summary>
        /// 保存角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult SaveRole(RoleModel model)
        {
            ResultData<int> rData = new ResultData<int>();
            GovRole info = new GovRole();
            try
            {
                if (model.roleID < 1)
                {

                    info.RoleTypeID = model.selRoleType;
                    info.IsActive = 1;
                    info.CreatedTime = DateTime.Now;
                    info.RoleName = model.roleName;
                    info.UpdatedTime = DateTimeHelper.MinDateTime();
                    object id = roleService.Insert(info);
                    loService.Info(CurrentUser.UserId, "添加角色", 1, "添加成功,返回ID:" + id, string.Format("{0}添加角色{1}", CurrentUser.UserName, info.RoleName), Rcode);
                    lsService.Info(CurrentUser.UserId, "添加角色", 1, "添加成功,返回ID:" + id, string.Format("{0}添加角色{1}", CurrentUser.UserName, info.RoleName), Rcode);

                }
                else
                {
                    info = roleService.Single(model.roleID);
                    info.RoleTypeID = model.selRoleType;
                    info.RoleName = model.roleName;
                    info.UpdatedTime = DateTime.Now;
                    roleService.Update(info);
                    loService.Info(CurrentUser.UserId, "修改角色", 3, "修改成功", string.Format("{0}修改角色,数据ID:{1}", CurrentUser.UserName, info.RoleID), Rcode);
                    lsService.Info(CurrentUser.UserId, "修改角色", 3, "修改成功", string.Format("{0}修改角色,数据ID:{1}", CurrentUser.UserName, info.RoleID), Rcode);

                }
            }
            catch (Exception ex)
            {
                rData.status = -1;
                rData.message = ex.Message;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelRole(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            GovRole info = roleService.Single(id);
            if (info != null)
            {
                info.IsActive = 0;
                info.UpdatedTime = DateTime.Now;
                roleService.Update(info);
                relaService.DeleteRoleMenu(id);
                rData.data = true;
                loService.Info(CurrentUser.UserId, "删除角色", 2, "删除成功", string.Format("{0}删除角色({1}),数据ID:{2}", CurrentUser.UserName, info.RoleName, info.RoleID), Rcode);
                lsService.Info(CurrentUser.UserId, "删除角色", 2, "删除成功", string.Format("{0}删除角色({1}),数据ID:{2}", CurrentUser.UserName, info.RoleName, info.RoleID), Rcode);

            }
            else
            {
                rData.status = -1;
                rData.data = false;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 验证编码是否重复
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult IsExistRoleName(int mid, string name)
        {
            ResultData<string> rData = new ResultData<string>();
            if (mid > 0)
            {
                //修改时先验证是否跟当前代码相同，如果不同则验证是否重复
                GovRole menuObj = roleService.Single(mid);
                if (menuObj != null)
                {
                    if (menuObj.RoleName != name)
                    {
                        bool isExist = roleService.CheckRoleName(name);
                        if (!isExist)
                        {
                            rData.status = -1;
                            rData.message = "名称不存在";
                        }
                    }
                    else
                    {
                        rData.status = -1;
                        rData.message = "修改时名称没变化";
                    }
                }
            }
            else
            {
                bool isExist = roleService.CheckRoleName(name);
                if (!isExist)
                {
                    rData.status = -1;
                    rData.message = "名称不存在";
                }
            }
            return ReturnResult(rData);
        }
        #endregion

        #region 权限配置
        [Authentication(MenuCode = 10103)]
        public ActionResult RoleMenuRelaEdit(int roleid)
        {
            @ViewBag.RoleId = roleid;
            loService.Info(CurrentUser.UserId, "访问页面", 4, "", "配置角色权限", Rcode);
            lsService.Info(CurrentUser.UserId, "访问页面", 4, "", "配置角色权限", Rcode);
            return View();
        }

        /// <summary>
        /// 保存权限配置
        /// </summary>
        [HttpPost]
        public ContentResult SaveRoleMenu(RoleMenuRelaModel model)
        {
            ResultData<int> rData = new ResultData<int>();
            int RoleID = model.RoleID;
            string des = "配置成功";
            if (RoleID > 0 && !string.IsNullOrEmpty(model.ChkMenuIds))
            {
                relaService.DeleteRoleMenu(RoleID);
                string[] strFIDAll = model.ChkMenuIds.Split(',');
                foreach (string strID in strFIDAll)
                {
                    if (strID == "") continue;
                    GovRoleMenuRela info = new GovRoleMenuRela
                    {
                        RoleID = model.RoleID,
                        MenuID = int.Parse(strID),
                        IsActive = 1,
                        CreateDateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };
                    relaService.Insert(info);
                }
            }
            else
            {
                rData.status = -1;
                rData.message = "请正确操作";
                des = "配置失败";
            }
          
            loService.Info(CurrentUser.UserId, "添加角色权限", 1, des, string.Format("{0},角色{1},配置权限{2}", CurrentUser.UserName, model.RoleID, model.ChkMenuIds), Rcode);
            lsService.Info(CurrentUser.UserId, "添加角色权限", 1, des, string.Format("{0},角色{1},配置权限{2}", CurrentUser.UserName, model.RoleID, model.ChkMenuIds), Rcode);

            return ReturnResult(rData);
        }
        #endregion


    }
}